package com.mogist.hqc.module.community.ui

import android.app.Dialog
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.CommunityDetailVo
import com.mogist.hqc.module.community.adapter.CommunityCommentAdapter
import com.mogist.hqc.module.community.adapter.CommunityIMGAdapter
import com.mogist.hqc.module.community.contract.CommunityDetailContract
import com.mogist.hqc.module.community.presenter.CommunityDetailPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.test.TestDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.CircleImageView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_comment_list.*
import kotlinx.android.synthetic.main.activity_community_detail.*
import kotlinx.android.synthetic.main.activity_community_detail.mSwipeToLoadLayout
import kotlinx.android.synthetic.main.activity_community_detail.mTvToComment
import kotlinx.android.synthetic.main.activity_community_detail.swipe_target
import kotlinx.android.synthetic.main.include_title.*
import org.jetbrains.anko.contentView
import talex.zsw.basecore.util.BitmapTool
import talex.zsw.basecore.util.DataTool
import talex.zsw.basecore.util.KeyboardTool
import talex.zsw.basecore.util.RegTool
import talex.zsw.basecore.util.glide.GlideApp
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.other.swipetoloadlayout.OnLoadMoreListener
import talex.zsw.basecore.view.other.swipetoloadlayout.OnRefreshListener
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.FullyLinearLayoutManager
import talex.zsw.basecore.view.recyleview.SampleFooter

/**
 * 作用：微社区 - 详情
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class CommunityDetailActivity : BaseMVPActivity<CommunityDetailContract.Presenter>(), CommunityDetailContract.View, OnRefreshListener, OnLoadMoreListener
{
    private var id = ""
    private var self = false
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("id")
                ?.let {
                    id = it
                }
        self = intent.getBooleanExtra("self",false)
    }

    override fun initView()
    {
        setContentView(R.layout.activity_community_detail)
        mPresenter = CommunityDetailPresenter(this)
    }

    override fun initData()
    {
        mTitleBar.setTitle("帖子详情")
        if (self)
        {
            mTvToComment.visibility = View.GONE
        }
        initRecyclerView()
        getData(false)
    }

    @Optional
    @OnClick(R.id.mTvToComment,
             R.id.mIvComment,
             R.id.mTvComment,
             R.id.mIvShare,
             R.id.mIvStar,
             R.id.mTvStar)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvToComment, R.id.mIvComment, R.id.mTvComment ->
                { // 评论
                    if (!self)
                    {
                        if (isLogin)
                        {
                            showCommentDialog()
                        }
                    }
                }
                R.id.mIvStar, R.id.mTvStar                          ->
                { // TODO 收藏(微社区没有收藏)
                    RxToast.normal("收藏?")
                }
                R.id.mIvShare                                       ->
                { // 微社区分享
                    showShareDialog(Util.createScreenShotBitmap(this@CommunityDetailActivity,
                                                                 BitmapTool.view2Bitmap(contentView)))
                }
            }
        }
    }

    private val adapter = CommunityCommentAdapter()
    private val imgAdapter = CommunityIMGAdapter()

    private fun initRecyclerView()
    {
        adapter.isUseEmpty(false)
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        swipe_target.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                             R.color.line))
        swipe_target.layoutManager = LinearLayoutManager(this@CommunityDetailActivity)
        swipe_target.adapter = adapter

        mSwipeToLoadLayout.setOnRefreshListener(this)
        mSwipeToLoadLayout.setOnLoadMoreListener(this)
        mSwipeToLoadLayout.isLoadMoreEnabled = false
        mSwipeToLoadLayout.isRefreshEnabled = false
        initHead()
    }

    private var headView: View? = null
    private var mIvIcon: CircleImageView? = null
    private var mTvName: TextView? = null
    private var mTvTime: TextView? = null
    private var mTvTitle: TextView? = null
    private var mIvInfo: TextView? = null
    private var mRecyclerView: RecyclerView? = null
    private var mTvCommentTitle: TextView? = null
    private fun initHead()
    {
        headView = layoutInflater.inflate(R.layout.head_community_detail, null)
        mIvIcon = headView?.findViewById(R.id.mIvIcon)
        mTvName = headView?.findViewById(R.id.mTvName)
        mTvTime = headView?.findViewById(R.id.mTvTime)
        mTvTitle = headView?.findViewById(R.id.mTvTitle)
        mIvInfo = headView?.findViewById(R.id.mIvInfo)
        mRecyclerView = headView?.findViewById(R.id.mRecyclerView)
        mTvCommentTitle = headView?.findViewById(R.id.mTvCommentTitle)

        imgAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRecyclerView?.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                               R.color.transparent))
        mRecyclerView?.layoutManager = FullyLinearLayoutManager(this@CommunityDetailActivity)
        mRecyclerView?.adapter = imgAdapter

        adapter.addHeaderView(headView)
    }

    override fun bindDetail(data: CommunityDetailVo)
    {
        mIvIcon?.let {
            GlideApp.with(it.context)
                    .load(data.userHead)
                    .centerCrop()
                    .into(it)
        }
        mTvName?.text = DataTool.formatPhone(data.userName)
        mTvTitle?.text = data.title
        mIvInfo?.text = data.content
        mTvTime?.text = data.createTime
        mTvComment?.text = data.sayNum
        imgAdapter.replaceData(data.userPostingImgList)
        if (data.userPostingReplyList != null && data.userPostingReplyList.size > 0)
        {
            adapter.replaceData(data.userPostingReplyList)
        }
        else
        {
            mTvCommentTitle?.visibility = View.GONE
        }
        disDialog()
    }

    // --------------- 数据获取 ---------------
    override fun onDestroy()
    {
        super.onDestroy()
        adapter.removeAllFooterView()
        sampleFooter = null
    }

    override fun getData(silence: Boolean)
    {
        val body = BaseModel()
        body.pId = id
        mPresenter.getData(HttpDto(Constant.COMMUNITY_DETAIL, body).setType(HttpDto.GET).setFinish(
                true).setErrorTitle("获取微社区详情失败"))
    }

    var sampleFooter: SampleFooter? = null
    override fun bindData(list: ArrayList<TestDto>?)
    {
        adapter.isUseEmpty(true)
        if (list != null && list.isNotEmpty())
        {
            //            if (page == 1)
            //            {
            //                adapter.setNewData(list)
            //            }
            //            else
            //            {
            //                adapter.addData(list)
            //            }
            //            if ()
            //            {
            //                sampleFooter?:let {
            //                    sampleFooter = SampleFooter(this@CommunityDetailActivity)
            //                }
            //                adapter.setFooterView(sampleFooter)
            //                mSwipeToLoadLayout.isLoadMoreEnabled = false
            //            }
            page++
        }
        else
        {
            mSwipeToLoadLayout.isLoadMoreEnabled = false
        }
    }

    private var page = 1

    override fun disLoading()
    {
        mSwipeToLoadLayout.isLoadingMore = false
        mSwipeToLoadLayout.isRefreshing = false
    }

    override fun onRefresh()
    {
        adapter.removeAllFooterView()
        page = 1
        mSwipeToLoadLayout.isLoadMoreEnabled = true
        mSwipeToLoadLayout.isRefreshEnabled = true
        getData(true)
    }

    override fun onLoadMore()
    {
        getData(true)
    }

    // --------------- 评论 ---------------
    private var dialog: Dialog? = null
    private var dEditText: EditText? = null
    private var commentStr = ""
    private fun showCommentDialog()
    {
        dialog
                ?: let {
                    dialog = Dialog(this@CommunityDetailActivity, R.style.dialog)
                    dialog?.setContentView(R.layout.dialog_comment)
                    dialog?.setCanceledOnTouchOutside(true)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = dialog?.window!!.attributes
                    layoutParams.width = (display.width * 1).toInt()
                    // layoutParams.height = (display.height * 0.8f).toInt()
                    layoutParams.gravity = Gravity.BOTTOM
                    if (layoutParams.gravity == Gravity.BOTTOM)
                    {
                        layoutParams.y = 0
                    }
                    dialog?.window!!.attributes = layoutParams

                    dEditText = dialog?.findViewById<EditText>(R.id.dEditText)
                    dialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                commentStr =
                                        dEditText!!.text.toString()
                                                .trim()
                                if (RegTool.isEmpty(commentStr))
                                {
                                    RxToast.warning("请输入评论信息")
                                }
                                else
                                {
                                    val body = BaseModel(true)
                                    body.pdtId = id
                                    body.content = commentStr
                                    mPresenter.getData(HttpDto(Constant.COMMUNITY_COMMENT,
                                                               body).setErrorTitle("发表评论失败"))
                                }
                            }
                    dialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                dialog?.dismiss()
                            }
                }
        dEditText?.setText("")
        KeyboardTool.showSoftInput(this@CommunityDetailActivity, dEditText)
        dialog?.show()
    }

    override fun commentSuccess()
    {
        dialog?.dismiss()
        RxToast.success("评论成功")
        getData(false)
    }

    // --------------- 分享 ----------------
    private var shareDialog: Dialog? = null
    private var dImage: ImageView? = null
    private fun showShareDialog(bitmap: Bitmap)
    {
        shareDialog
                ?: let {
                    shareDialog = Dialog(this@CommunityDetailActivity, R.style.dialog)
                    shareDialog?.setContentView(R.layout.dialog_share)
                    shareDialog?.setCanceledOnTouchOutside(false)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = shareDialog?.window!!.attributes
                    layoutParams.width = (display.width * 0.8f).toInt()
                    layoutParams.height = (display.height * 0.9f).toInt()
                    shareDialog?.window!!.attributes = layoutParams
                    dImage = shareDialog?.findViewById(R.id.dImage)

                    shareDialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                showDialog()
                                Observable.just(bitmap)
                                        .subscribeOn(Schedulers.io())
                                        .map { v ->
                                            Uri.parse(MediaStore.Images.Media.insertImage(
                                                    contentResolver,
                                                    v,
                                                    null,
                                                    null))
                                        }
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe({ uri ->
                                                       disDialog()
                                                       val shareIntent = Intent()
                                                       shareIntent.action = Intent.ACTION_SEND
                                                       shareIntent.putExtra(Intent.EXTRA_STREAM,
                                                                            uri)
                                                       shareIntent.type = "image/*"
                                                       start(Intent.createChooser(shareIntent,
                                                                                  "分享到"))
                                                       shareDialog?.dismiss()
                                                   }) { t ->
                                            t.printStackTrace()
                                            disDialog()
                                            RxToast.error("分享失败")
                                        }
                            }
                    shareDialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                bitmap.recycle()
                                shareDialog?.dismiss()
                            }
                }
        dImage?.setImageBitmap(bitmap)
        shareDialog?.show()
    }
}